package com.yanqu.road.server.cmd.player;

import com.yanqu.road.entity.player.UserInfo;
import com.yanqu.road.utils.YanQuMessageUtils;
import com.yanqu.road.pb.player.PlayerProto;
import com.yanqu.road.server.GameServer;
import com.yanqu.road.server.cmd.base.AbstractCommand;
import com.yanqu.road.server.command.Cmd;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.manger.player.UserMgr;
import com.yanqu.road.server.manger.player.GamePlayerMgr;
import com.yanqu.road.message.YanQuMessage;
import com.yanqu.road.server.protocol.Protocol;

@Cmd(code = Protocol.S_WATCH_PLAYER_PATRONS, desc = "拜访玩家门客")
public class WatchPlayerPatronsCmd extends AbstractCommand {

	private long watchUserId;

	private long watchServerId;

	private int patronsId;

	private String watchPlayerResult;

	@Override
	public boolean parseData(YanQuMessage packet) throws Exception {
		PlayerProto.WatchPlayerPatronsReqMsg reqMsg = PlayerProto.WatchPlayerPatronsReqMsg.parseFrom(packet.getBytes());
		watchUserId = reqMsg.getUserId();
		watchServerId = reqMsg.getServerId();
		if(watchServerId == 0){
			watchServerId = GameServer.getInstance().getServerId();
		}
		patronsId = reqMsg.getPatronsId();
		return true;
	}

	@Override
	public void execute(GamePlayer player, YanQuMessage packet) throws Exception {
		if(watchServerId == GameServer.getInstance().getServerId()) {//本服逻辑
			if (player.getUserId() == watchUserId) {
				return;
			}
			watchPlayerResult = UserMgr.watchPlayerPatron(watchUserId,patronsId);
		}else {//跨服逻辑
			PlayerProto.WatchPlayerPatronsReqMsg.Builder msg = PlayerProto.WatchPlayerPatronsReqMsg.newBuilder();
			msg.setUserId(watchUserId);
			msg.setServerId(watchServerId);
			msg.setPatronsId(patronsId);
			YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.C_CROSS_WATCH_PLAYER_PATRONS, msg);
			GamePlayerMgr.sendPacket(player.getUserId(), pbMsg);
		}
	}

	@Override
	public void sendData(GamePlayer player) {
		if(watchServerId == GameServer.getInstance().getServerId()) {//本服逻辑
			PlayerProto.WatchPlayerPatronsRespMsg.Builder respMsg = PlayerProto.WatchPlayerPatronsRespMsg.newBuilder();
			respMsg.setUserId(watchUserId);
			respMsg.setServerId(watchServerId);
			UserInfo userInfo = UserMgr.getUserInfo(watchUserId);
			respMsg.setNickName(userInfo.getNickName());
			respMsg.setPatronsId(patronsId);
			respMsg.setPatronsInfo(watchPlayerResult);
			player.sendPacket(Protocol.U_WATCH_PLAYER_PATRONS, respMsg);
		}
	}
}
